//
//  QScanCodeVC.m
//  QoilPublic
//
//  Created by 杨凯 on 16/7/21.
//  Copyright © 2016年 杨凯. All rights reserved.
//

#import "QScanCodeVC.h"
#import <AVFoundation/AVFoundation.h>
#import "QScanMaskView.h"
#import "QScanInforMationVC.h"
#import "QWebViewVC.h"
#import "QRegisterVC.h"
@interface QScanCodeVC ()<AVCaptureMetadataOutputObjectsDelegate>

@property (nonatomic,strong)AVCaptureSession * session;

@property(nonatomic,strong)UIImageView *scanImageView;

@end

@implementation QScanCodeVC{
    
    UIImageView *line;
}

- (void)viewWillAppear:(BOOL)animated{
    
    [super viewWillAppear:animated];
    if(!_ispush){
        [_session startRunning];
        [self addAnmation];
    }
}
- (void)viewDidDisappear:(BOOL)animated{
    [super viewDidDisappear:animated];
    _ispush = NO;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"二维码扫描";
    [self createUI];
    [self createScan];
}

- (void)createUI{
    
    _scanImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 220, 220)];
    _scanImageView.center = self.view.center;
    _scanImageView.backgroundColor = [UIColor clearColor];
    _scanImageView.image = [UIImage imageNamed:@"scan_space"];
    _scanImageView.clipsToBounds = YES;
    [self.view addSubview:_scanImageView];
    
    UILabel *titleLabel = [QViewUtility createLabelWithFrame:CGRectMake(0, _scanImageView.bottom+20, kScreenWidth, 20) font:Ksize13 textAlignment:NSTextAlignmentCenter textColor:[UIColor whiteColor] text:@"将二维码放入框内,即可自动扫描"];
    [self.view addSubview:titleLabel];
    
    line = [[UIImageView alloc] initWithFrame:CGRectMake(10,0,200,5)];
    line.image = [UIImage imageNamed:@"scan_line"];
    [_scanImageView addSubview:line];
    
    [self addAnmation];
    
    QScanMaskView *maskView = [[QScanMaskView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight)];
    maskView.cropRect = _scanImageView.frame;
    maskView.backgroundColor = [UIColor colorWithWhite:0 alpha:0.4];
    [self.view addSubview:maskView];
}

- (void)addAnmation{
    
    CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"transform.translation.y"];
    animation.duration = 2;
    animation.repeatCount = MAXFLOAT;
    animation.autoreverses = YES;
    animation.fromValue = 0;
    animation.toValue = @(215);
    [line.layer addAnimation:animation forKey:@"keyanimation"];
}

- (void)createScan{
    
    NSError *error;
    //获取摄像设备
    AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
    
    //创建输入流
    AVCaptureDeviceInput *input = [AVCaptureDeviceInput deviceInputWithDevice:device error:&error];
    
    //创建输出流
    AVCaptureMetadataOutput *output = [[AVCaptureMetadataOutput alloc] init];
    [output setMetadataObjectsDelegate:self queue:dispatch_get_main_queue()];//设置代理 在主线程里刷新
    CGRect scanImageRect = _scanImageView.frame;
    CGSize size = self.view.bounds.size;
    output.rectOfInterest = CGRectMake(scanImageRect.origin.y/size.height, scanImageRect.origin.x/size.width, scanImageRect.size.width/size.height, scanImageRect.size.height/size.width);
    
    //初始化链接对象
    _session = [[AVCaptureSession alloc] init];
    if ([_session canAddInput:input])
    {
        [_session addInput:input];
    }
    
    if ([_session canAddOutput:output])
    {
        [_session addOutput:output];
    }
    
    [output setMetadataObjectTypes:[NSArray arrayWithObject:AVMetadataObjectTypeQRCode]];//设置支持的扫描类型
    //显示
    AVCaptureVideoPreviewLayer *preview = [[AVCaptureVideoPreviewLayer alloc] initWithSession:_session];
    [preview setVideoGravity:AVLayerVideoGravityResizeAspectFill];
    preview.frame = self.view.bounds;
    [self.view.layer insertSublayer:preview atIndex:0];
    
    [_session startRunning];
}

#pragma mark --- 扫描后的结果delegate
- (void)captureOutput:(AVCaptureOutput *)captureOutput didOutputMetadataObjects:(NSArray *)metadataObjects fromConnection:(AVCaptureConnection *)connection{
    
    if(metadataObjects.count > 0){
        AVMetadataMachineReadableCodeObject *objc = [metadataObjects firstObject];
        CLog(@"====%@",objc.stringValue);
        
        if([objc.stringValue containsString:@"sevalo_ydaol"] && [objc.stringValue containsString:@"orderId"]){
            QScanInforMationVC *vc = [[QScanInforMationVC alloc] init];
            NSString *objcStr = objc.stringValue;
            NSArray *arr = [objcStr componentsSeparatedByString:@"?"];
            if(arr.count){
                NSString *s = arr[1];
                NSArray *a1 = [s componentsSeparatedByString:@"&"];
                if(a1.count){
                    NSString *s2 = a1[0];
                    NSArray *a2 = [s2 componentsSeparatedByString:@"="];
                    if(a2.count){
                        vc.sId = a2[1];
                    }
                }
            }
            if(![QUserInfo sharedInfo].loginModel){
                [self.navigationController popViewControllerAnimated:YES];
                [QViewUtility showPlayBoxView:PlayboxChangeMemberStyle myBlock:^(NSInteger index) {
                    if(index == 1){
                        if(_pushLoginBlock){
                            _pushLoginBlock();
                        }
                    }
                }];
            }else{
                [self.navigationController pushViewController:vc animated:YES];
            }
        }else if([objc.stringValue containsString:@"sevalo_ydaol=zhuce"]){
            QRegisterVC *vc = [[QRegisterVC alloc] initWithNibName:@"QRegisterVC" bundle:nil];
            NSString *objcStr = objc.stringValue;
            NSArray *arr = [objcStr componentsSeparatedByString:@"zhuce&tel="];
            if(arr.count){
                NSString *s = arr[1];
                vc.scanCodeStr = s;
                CLog(@"邀请码===%@",s);
            }
            [self.navigationController pushViewController:vc animated:YES];
        }else{
            QWebViewVC *vc = [[QWebViewVC alloc] init];
            vc.style = WebNetWorkStyle;
            vc.url = objc.stringValue;
            [self.navigationController pushViewController:vc animated:YES];
        }
    }
    [_session stopRunning];
}

@end
